<?php
declare (strict_types=1);

namespace app\admin\controller\tally;

use app\admin\controller\CommonController;
use app\common\model\AclUser;
use app\common\model\TallyCustom;
use app\common\model\TallyProgressMonth;
use think\db\BaseQuery;
use think\facade\Db;

class Custom extends CommonController
{
    protected $modelName = TallyCustom::MODEL_NAME;
    protected $alias = 'c';

    protected function buildWhere(array $param): array
    {
        $where = parent::buildWhere($param);
        if (auth('roleAccounting')) {
            $where[] = ["{$this->alias}.accounting_id", '=', currentUserId()];
        }
        return $where;
    }

    protected function getBaseModel(): BaseQuery
    {
        return parent::getBaseModel()
            ->leftJoin(AclUser::MODEL_NAME . ' a', "a.id={$this->alias}.accounting_id");
    }

    protected function getSearchFields(): string
    {
        return "{$this->alias}.*,concat(a.username,a.nickname) accounting_name";
    }

    protected function getFilterFields(): array
    {
        return ['id', 'accounting_id', 'number', 'name', 'estimate_time', 'contract_ids', 'status'];
    }

    protected function setDefaultValueInAddPage(array $row): array
    {
        $row['accounting_id'] = 0;
        $row['estimate_time'] = sysValue('default_custom_estimate_time');
        $this->assign('contracts', []);
        return parent::setDefaultValueInAddPage($row);
    }

    protected function editPage(array $row)
    {
        $contracts = [];
        if (!empty($row['contract_ids'])) {
            $contracts = Db::name('system_uploadfile')->whereIn('id', $row['contract_ids'])->select()->toArray();
        }
        $this->assign('contracts', $contracts);
        return parent::editPage($row);
    }

    protected function onAfterEdit(array &$data, array $row)
    {
        TallyProgressMonth::updateAccountingId($data['id'], $data['accounting_id']);
        parent::onAfterEdit($data, $row);
    }

    protected function onBeforeDelete($id): array
    {
        // 判断存在月进度表
        if (TallyProgressMonth::findByCustomId($id)) {
            $this->error(lang('custom.error_exist_progress_month'));
        }
        return parent::onBeforeDelete($id);
    }
}
